package com.example.student_blocket;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/*
 * @author Hamed Talebi
 * Date: 18/03/14
 */
public class DatabaseHandler {
	public static final String KEY_ROWID = "_id";
	public static final String KEY_USERNAME = "user_name";
	public static final String KEY_CHECKED = "save_checkbox";

	private static final String DATABASE_NAME = "project";
	private static final String DATABASE_TABLE = "userData";
	private static final int DATABASE_VERSION = 1;
	
	private DbHelper ourHelper;
	private final Context ourContext;
	private SQLiteDatabase ourDatabase;
	
	private static class DbHelper extends SQLiteOpenHelper {

		public DbHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_USERNAME
					+ " TEXT NOT NULL, " + KEY_CHECKED + " TEXT NOT NULL);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
			db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
			onCreate(db);
		}

	}
	
	public DatabaseHandler (Context c) {
		ourContext = c;
	}
	
	public DatabaseHandler open() throws SQLException{
		ourHelper = new DbHelper(ourContext);
		ourDatabase = ourHelper.getWritableDatabase();
		return this;
	}
	
	public void close(){
		ourHelper.close();
	}
	
	public long createEntry(String name, String checked) {
		ContentValues cv = new ContentValues();
		cv.put(KEY_USERNAME, name);
		cv.put(KEY_CHECKED, checked);
		return ourDatabase.insert(DATABASE_TABLE, null, cv);
	}
	
	public String getUserName(int l) throws SQLException{
		String[] columns = new String[]{KEY_ROWID, KEY_USERNAME, KEY_CHECKED};
		Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
		if(c != null){
			c.moveToFirst();
			String name = c.getString(1);
			return name;
		}
		return null;
	}

	public String getCheckStatus(int l) throws SQLException{
		String[] columns = new String[]{KEY_ROWID, KEY_USERNAME, KEY_CHECKED};
		Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
		if(c != null){
			c.moveToFirst();
			String checked = c.getString(2);
			return checked;
		}
		return null;
	}
	
	public void updateEntry(long mRow, String mUserName, String mChecked) throws SQLException{
		ContentValues cvUpdate = new ContentValues();
		cvUpdate.put(KEY_USERNAME, mUserName);
		cvUpdate.put(KEY_CHECKED, mChecked);
		ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + mRow, null);
	}
}
